import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONString;

import com.sun.sgs.client.ClientChannel;
import com.sun.sgs.client.simple.SimpleClient;

class DarkstarAuthenticationException extends Exception {
} // Darkstar Server

class TCGAuthenticationException extends Exception {
} // TCG Server

public class AgentProcessor {

	private String getStringFromJson(JSONObject json, String attribute) {
		try {
			return (String) json.getJSONArray(attribute).get(0);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void processCommand(JSONObject jsonObject)
			throws InterruptedException, JSONException {
		String cmd = getStringFromJson(jsonObject, "cmd");
		if (("LOGIN").equals(cmd.toString())) {
			try {
				processLogin(jsonObject);
			} catch (TCGAuthenticationException e) {
				e.printStackTrace();
			} catch (DarkstarAuthenticationException e) {
				e.printStackTrace();
			}
		}
//		else if (darkstarBridge.isConnected()) {
		// if (("DISCONNECT").equals(cmd)) {
		// darkstarBridge.getSimpleClient().logout(false);
		// } else if (cmd.equals("CHAT")) {
		// ClientChannel channel =
		// (darkstarBridge.getChannelMap()).get(
		// jsonObject.getString("channelName"));
		// channel.send(
		// darkstarBridge.encodeString(
		// jsonObject.getString("chatMessage")));
		// /** the above might need to be reworked */
		// } else if (cmd.equals("LOAD_PLAYER_DECK")) {
		// processPlayerDecks();
		// } else if (("LOAD_PLAYER_DECKCARDS").equals(cmd)) {
		// processDeckCards(jsonObject.getInt("deckId"));
		// } else if (cmd.equals("START_BATTLE")) {
		// } else if (cmd.equals("RECORD_BATTLE_RESULT")) {
		// } else {
		// darkstarBridge.sendSessionMsgToDarkstar(jsonObject.toString());
		// }
		// }
		// }
		// catch (Exception e) {
		// e.printStackTrace();
		// }
	}

	private void processLogin(JSONObject inputJson)
			throws TCGAuthenticationException, DarkstarAuthenticationException {
		try {
			String userId = getStringFromJson(inputJson, "username");
			String password = getStringFromJson(inputJson, "password");
			JSONObject jsonObject = new JSONObject();
			if (loginTCG(userId, password)) {
				if (loginDarkstar(userId, password)) {
					jsonObject.put("cmd", "LOGIN_SUCCESS");
					jsonObject.put("username", userId);
					System.out.println("User " + userId
							+ " logged Successfully");
					// darkstarBridge.sendToAgent(jsonObject.toString()); //
					// TODO
					// loadLoginSequence(userId);
					// getPlayerInitData(userId);
				} else {
					jsonObject.put("cmd", "LOGIN_FAILURE_DS");
					jsonObject.put("username", userId);
					// darkstarBridge.sendToAgent(jsonObject.toString()); //
					// TODO
					System.err.println("Login to Darkstar failed");
					throw new DarkstarAuthenticationException();
				}
			} else {
				jsonObject.put("cmd", "LOGIN_FAILURE_TCG");
				jsonObject.put("username", userId);
				// darkstarBridge.sendToAgent(jsonObject.toString());// TODO
				System.err.println("Login to TCG failed");
				throw new TCGAuthenticationException();
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	public boolean loginTCG(String userId, String password) {
		boolean loginSuccessful = false;
		CharSequence charSequence = "loginOK=true";
		String tempString = "";
		BufferedReader in;
		try {
			URLConnection urlConnection = new URL(
					"http://tcg.dyndns.info:8081/mcslcard/JSP/Login_flash.jsp?acc="
							+ userId + "&pwd=" + password).openConnection();
			in = new BufferedReader(new InputStreamReader(
					(InputStream) urlConnection.getContent()));
			while ((tempString = in.readLine()) != null) {
				if (tempString.contains(charSequence)) {
					loginSuccessful = true;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return loginSuccessful;
	}

	private boolean loginDarkstar(String userId, String password) {
		String host = "tcg.dyndns.info";
		String port = "842";
		SimpleClient playerClient = null;
		try {
			Properties connectProps = new Properties();
			connectProps.put("host", host);
			connectProps.put("port", port);
			Player player = new Player(userId, password);
			playerClient = PlayerController.getOrCreatePlayerClient(player);
			playerClient.login(connectProps);
			Thread.sleep(5000);
		} catch (Exception exception) {
			exception.printStackTrace();
			System.err.println(exception.getMessage());
		}
		return playerClient != null && playerClient.isConnected();
	}

}
